/*! @azure/msal-browser v2.38.3 2023-10-27 */
'use strict';
import { __awaiter, __generator, __spread, __assign } from '../_virtual/_tslib.js';
import { AccountEntity, AuthenticationScheme, ClientConfigurationError, StringUtils, PerformanceEvents, UrlString, ServerTelemetryManager, AuthorityFactory } from '@azure/msal-common';
import { version } from '../packageMetadata.js';
import { BrowserConstants } from '../utils/BrowserConstants.js';
import { BrowserUtils } from '../utils/BrowserUtils.js';

/*
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License.
 */
var BaseInteractionClient = /** @class */ (function () {
    function BaseInteractionClient(config, storageImpl, browserCrypto, logger, eventHandler, navigationClient, performanceClient, nativeMessageHandler, correlationId) {
        this.config = config;
        this.browserStorage = storageImpl;
        this.browserCrypto = browserCrypto;
        this.networkClient = this.config.system.networkClient;
        this.eventHandler = eventHandler;
        this.navigationClient = navigationClient;
        this.nativeMessageHandler = nativeMessageHandler;
        this.correlationId = correlationId || this.browserCrypto.createNewGuid();
        this.logger = logger.clone(BrowserConstants.MSAL_SKU, version, this.correlationId);
        this.performanceClient = performanceClient;
    }
    BaseInteractionClient.prototype.clearCacheOnLogout = function (account) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!account) return [3 /*break*/, 5];
                        if (AccountEntity.accountInfoIsEqual(account, this.browserStorage.getActiveAccount(), false)) {
                            this.logger.verbose("Setting active account to null");
                            this.browserStorage.setActiveAccount(null);
                        }
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        return [4 /*yield*/, this.browserStorage.removeAccount(AccountEntity.generateAccountCacheKey(account))];
                    case 2:
                        _a.sent();
                        this.logger.verbose("Cleared cache items belonging to the account provided in the logout request.");
                        return [3 /*break*/, 4];
                    case 3:
                        _a.sent();
                        this.logger.error("Account provided in logout request was not found. Local cache unchanged.");
                        return [3 /*break*/, 4];
                    case 4: return [3 /*break*/, 9];
                    case 5:
                        _a.trys.push([5, 8, , 9]);
                        this.logger.verbose("No account provided in logout request, clearing all cache items.", this.correlationId);
                        // Clear all accounts and tokens
                        return [4 /*yield*/, this.browserStorage.clear()];
                    case 6:
                        // Clear all accounts and tokens
                        _a.sent();
                        // Clear any stray keys from IndexedDB
                        return [4 /*yield*/, this.browserCrypto.clearKeystore()];
                    case 7:
                        // Clear any stray keys from IndexedDB
                        _a.sent();
                        return [3 /*break*/, 9];
                    case 8:
                        _a.sent();
                        this.logger.error("Attempted to clear all MSAL cache items and failed. Local cache unchanged.");
                        return [3 /*break*/, 9];
                    case 9: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Initializer function for all request APIs
     * @param request
     */
    BaseInteractionClient.prototype.initializeBaseRequest = function (request, account) {
        return __awaiter(this, void 0, void 0, function () {
            var authority, scopes, validatedRequest, _a;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        this.performanceClient.addQueueMeasurement(PerformanceEvents.InitializeBaseRequest, request.correlationId);
                        this.logger.verbose("Initializing BaseAuthRequest");
                        authority = request.authority || this.config.auth.authority;
                        if (!account) return [3 /*break*/, 2];
                        return [4 /*yield*/, this.validateRequestAuthority(authority, account)];
                    case 1:
                        _b.sent();
                        _b.label = 2;
                    case 2:
                        scopes = __spread(((request && request.scopes) || []));
                        validatedRequest = __assign(__assign({}, request), { correlationId: this.correlationId, authority: authority,
                            scopes: scopes });
                        // Set authenticationScheme to BEARER if not explicitly set in the request
                        if (!validatedRequest.authenticationScheme) {
                            validatedRequest.authenticationScheme = AuthenticationScheme.BEARER;
                            this.logger.verbose("Authentication Scheme wasn't explicitly set in request, defaulting to \"Bearer\" request");
                        }
                        else {
                            if (validatedRequest.authenticationScheme === AuthenticationScheme.SSH) {
                                if (!request.sshJwk) {
                                    throw ClientConfigurationError.createMissingSshJwkError();
                                }
                                if (!request.sshKid) {
                                    throw ClientConfigurationError.createMissingSshKidError();
                                }
                            }
                            this.logger.verbose("Authentication Scheme set to \"" + validatedRequest.authenticationScheme + "\" as configured in Auth request");
                        }
                        if (!(this.config.cache.claimsBasedCachingEnabled && request.claims && !StringUtils.isEmptyObj(request.claims))) return [3 /*break*/, 4];
                        _a = validatedRequest;
                        return [4 /*yield*/, this.browserCrypto.hashString(request.claims)];
                    case 3:
                        _a.requestedClaimsHash = _b.sent();
                        _b.label = 4;
                    case 4: return [2 /*return*/, validatedRequest];
                }
            });
        });
    };
    /**
     *
     * Use to get the redirect uri configured in MSAL or null.
     * @param requestRedirectUri
     * @returns Redirect URL
     *
     */
    BaseInteractionClient.prototype.getRedirectUri = function (requestRedirectUri) {
        this.logger.verbose("getRedirectUri called");
        var redirectUri = requestRedirectUri || this.config.auth.redirectUri || BrowserUtils.getCurrentUri();
        return UrlString.getAbsoluteUrl(redirectUri, BrowserUtils.getCurrentUri());
    };
    /*
     * If authority provided in the request does not match environment/authority specified
     * in the account or MSAL config, we throw an error.
     */
    BaseInteractionClient.prototype.validateRequestAuthority = function (authority, account) {
        return __awaiter(this, void 0, void 0, function () {
            var discoveredAuthority;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.getDiscoveredAuthority(authority)];
                    case 1:
                        discoveredAuthority = _a.sent();
                        if (!discoveredAuthority.isAlias(account.environment)) {
                            throw ClientConfigurationError.createAuthorityMismatchError();
                        }
                        return [2 /*return*/];
                }
            });
        });
    };
    /**
     *
     * @param apiId
     * @param correlationId
     * @param forceRefresh
     */
    BaseInteractionClient.prototype.initializeServerTelemetryManager = function (apiId, forceRefresh) {
        this.logger.verbose("initializeServerTelemetryManager called");
        var telemetryPayload = {
            clientId: this.config.auth.clientId,
            correlationId: this.correlationId,
            apiId: apiId,
            forceRefresh: forceRefresh || false,
            wrapperSKU: this.browserStorage.getWrapperMetadata()[0],
            wrapperVer: this.browserStorage.getWrapperMetadata()[1]
        };
        return new ServerTelemetryManager(telemetryPayload, this.browserStorage);
    };
    /**
     * Used to get a discovered version of the default authority.
     * @param requestAuthority
     * @param requestCorrelationId
     */
    BaseInteractionClient.prototype.getDiscoveredAuthority = function (requestAuthority) {
        return __awaiter(this, void 0, void 0, function () {
            var authorityOptions;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.logger.verbose("getDiscoveredAuthority called");
                        authorityOptions = {
                            protocolMode: this.config.auth.protocolMode,
                            knownAuthorities: this.config.auth.knownAuthorities,
                            cloudDiscoveryMetadata: this.config.auth.cloudDiscoveryMetadata,
                            authorityMetadata: this.config.auth.authorityMetadata
                        };
                        if (!requestAuthority) return [3 /*break*/, 2];
                        this.logger.verbose("Creating discovered authority with request authority");
                        return [4 /*yield*/, AuthorityFactory.createDiscoveredInstance(requestAuthority, this.config.system.networkClient, this.browserStorage, authorityOptions, this.logger)];
                    case 1: return [2 /*return*/, _a.sent()];
                    case 2:
                        this.logger.verbose("Creating discovered authority with configured authority");
                        return [4 /*yield*/, AuthorityFactory.createDiscoveredInstance(this.config.auth.authority, this.config.system.networkClient, this.browserStorage, authorityOptions, this.logger)];
                    case 3: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    return BaseInteractionClient;
}());

export { BaseInteractionClient };
//# sourceMappingURL=BaseInteractionClient.js.map
